var QQMapWX = require('../../utils/qqmap-wx-jssdk.js');
var qqmapsdk;
var interval = 0,
  page_first_init = !0,
  timer = 1,
  timer1 = 2,
  fullScreen = !1,
  page_first = [],
  e = !1;
var systemInfo = getApp().core.getSystemInfoSync();
function secondToTimeStr(t) {
  if (t < 60) return "00:00:" + ((i = t) < 10 ? "0" + i : i);
  if (t < 3600) return "00:" + ((a = parseInt(t / 60)) < 10 ? "0" + a : a) + ":" + ((i = t % 60) < 10 ? "0" + i : i);
  if (3600 <= t) {
      var a, i, e = parseInt(t / 3600);
      return (e < 10 ? "0" + e : e) + ":" + ((a = parseInt(t % 3600 / 60)) < 10 ? "0" + a : a) + ":" + ((i = t % 60) < 10 ? "0" + i : i);
  }
}
Page({
  data: {
    windowWidth: systemInfo.windowWidth,
    WindowHeight: systemInfo.windowHeight,
    statusBarHeight: systemInfo.statusBarHeight,
    left: 0,
    show_notice: -1,
    animationData: {},
    play: -1,
    time: 0,
    buy: !1,
    opendate: !1,
    goods: "",
    form: {
      number: 1
    },
    time_all: [],
    shop_info:'',
    api_host: '',
    is_show_index_login_modal: true,
    select_active: 1,
    district:""
  },
  onLoad: function(t) {
    var that = this;
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })
    getApp().page.onLoad(this, t), t.page_id || (t.page_id = -1), this.setData({
      options: t,
      api_host: getApp().globalData.api_host
    });
    getApp().getStoreData();
    var user_info = getApp().getUser();
    qqmapsdk = new QQMapWX({
      key: '7PWBZ-EO7W4-DFLU2-DBF4P-SBVXE-W5FXE'
    });
    const _locationChangeFn = function(res) {
      qqmapsdk.reverseGeocoder({
        location: {
          latitude:res.latitude,
          longitude:res.longitude
        },
        success(res) {
          var address = res.result;
          that.setData({
            district: address.ad_info.district
          })

        },
        fail(err) {
          wx.showToast('获取地址失败')
        }
      });
      that.setData({
        latitude: res.latitude,
        longitude: res.longitude
      }),that.loadShop();
      wx.offLocationChange(_locationChangeFn)
      // that.loadData1();//秒杀
    }
    // console.log(getApp().globalData.checkLogin)
    // if (!getApp().globalData.checkLogin){
    //   getApp().checkLoginReadyCallback = res => {
    //       //登陆成功后执行的
    //       that.loadData1(); //秒杀;该接口有token验证，需登录之后才能查到数据
    //   };
    // }
    // if (user_info && user_info.parent_mch_id > 0 &&   !getApp().globalData.is_first_index) {
    //  getApp().globalData.is_first_index = true;
    //   wx.redirectTo({
    //     url: '/mch/shop/shop?mch_id=' + user_info.parent_mch_id,
    //   });
    // } 
    // else if (getApp().globalData.is_redirected_mch && this.data.store.is_mch_mode  == 1 ) {
    //   wx.getLocation({
    //     success: function (loca) {
    //       var longitude = loca.longitude;
    //       var latitude = loca.latitude;
    //       console.log(loca)
    //       wx.showLoading({
    //         title: "加载中"
    //       });
    //       getApp().request({
    //         url: getApp().api.mch.mch_list,
    //         method: "GET",
    //         data: {
    //           longitude: longitude,
    //           latitude: latitude
    //         },
    //         success: function (res) {
    //           if (res.code == 0 && res.data.list.length > 0) {
    //             var mch_id = res.data.list[0].id;
    //             wx.redirectTo({
    //               url: '/mch/shop/shop?mch_id=' + mch_id,
    //             });
    //           } else {
    //             this.loadData(t);
    //           }
    //         },
    //         fail: function (res) { },
    //         complete: function () {
    //           wx.hideLoading();
    //         }
    //       });
    //     }
    //   });
    // } else {
      wx.startLocationUpdate({
        success: (res) => {
          wx.onLocationChange(_locationChangeFn);
        }
      })
      this.loadData(t);
      this.seachRecommend();
      // this.loadkjData();//砍价
    // }
  },
  seachRecommend: function () {
    var that = this;
    getApp().request({
      url: getApp().api.default.recommend_course,
      data: {
        page: 1
      },
      method: "POST",
      success: function(t) {
        if (0 == t.code) {
          var list = t.data.list.length&&t.data.list.length>0?t.data.list:[];
          that.setData({
            recommend: list
          })
        }
      },
    });
  },
  editPrice:function (str){
    var str = str.toFixed(1);
    return str
  },
  navigatorGoods:function(e){
    getApp().core.navigateTo({
      url: '/pages/goods/goods?id=' + e.currentTarget.dataset.id
    });
  },
  selectActive: function (e) {
    var active = e.currentTarget.dataset.active;
    this.setData({
      select_active: active
    });
    // if(active==1){
    //   this.loadData1()
    // }else{
    //   this.loadkjData()
    // }
  },
  loadData1: function(t) {
    var a = this;
    getApp().request({
        url: getApp().api.miaosha.list,
        success: function(t) {
            if (0 == t.code) if (0 == t.data.list.length) {
                if (0 == t.data.next_list.length) return void getApp().core.showModal({
                    content: "暂无秒杀活动",
                    showCancel: !1,
                    confirmText: "返回首页",
                    success: function(t) {
                        t.confirm && getApp().core.switchTab({
                            url: "/pages/index/index"
                        });
                    }
                });
                a.setData({
                    goods_list: t.data.next_list.list,
                    ms_active: !0,
                    time_list: t.data.list,
                    next_list: t.data.next_list.list,
                    next_time: t.data.next_list.time
                });
                

            } else a.setData({
                time_list: t.data.list,
                next_list: "" == t.data.next_list ? [] : t.data.next_list.list,
                next_time: "" == t.data.next_list ? [] : t.data.next_list.time,
                ms_active: !1
            }), a.setTimeOver(), a.loadGoodsList(!1);
            1 == t.code && getApp().core.showModal({
                title: "提示",
                content: t.msg,
                success: function() {
                    getApp().core.switchTab({
                        url: "/pages/index/index"
                    });
                },
                showCancel: !1
            });
        }
    });
  },
  setTimeOver: function() {
    var e = this;
    function t() {
        for (var t in e.data.time_list) {
            e.data.time_list[t].now_time = Date.parse(new Date())/1000;
            var a = e.data.time_list[t].begin_time - e.data.time_list[t].now_time, i = e.data.time_list[t].end_time - e.data.time_list[t].now_time;

            if(i<=0&&e.data.time_list[t].active){
              e.loadData1();
              return;
            }
            a = 0 < a ? a : 0, i = 0 < i ? i : 0, e.data.time_list[t].begin_time_over = secondToTimeStr(a), 
            e.data.time_list[t].end_time_over = secondToTimeStr(i);
            // e.data.time_list[t].now_time = e.data.time_list[t].now_time + 1;
        }
        e.setData({
            time_list: e.data.time_list
        });
    }
    t(), timer1 = setInterval(function() {
        t();
    }, 1e3);
  },
  loadGoodsList: function(a) {
    var i = this, t = !1;
    for (var e in i.data.time_list) {
        if (i.data.time_list[e].active) {
            t = i.data.time_list[e].start_time;
            break;
        }
        i.data.time_list.length == parseInt(e) + 1 && 0 == t && (t = i.data.time_list[0].start_time, 
        i.data.time_list[0].active = !0);
    }
    a ? i.setData({
        loading_more: !0
    }) : i.setData({
        goods_list: null
    }), getApp().request({
        url: getApp().api.miaosha.goods_list,
        data: {
            time: t,
            page: 1,
            sort:0
        },
        success: function(t) {
            0 == t.code && (i.data.goods_list = a ? i.data.goods_list.concat(t.data.list) : t.data.list, 
            i.setData({
                loading_more: !1,
                goods_list: i.data.goods_list,
                page: t.data.list && 0 != t.data.list.length ? i.data.page + 1 : -1
            }));
        }
    });
  },
  goToGoods: function(o) {
    var t = o.currentTarget.dataset.index;
    var mch_id = o.currentTarget.dataset.mch_id;
    console.log(mch_id)
    getApp().core.navigateTo({
      url: "/bargain/goods/goods?goods_id=" + t + '&mch_id=' + mch_id
    });
  },
  loadkjData: function() {
        var a = this;
        getApp().request({
            url: getApp().api.bargain.index,
            data: {
                page: 1,
                sort:1
            },
            success: function(o) {
                if (0 == o.code) {
                    var t = o.data.goods_list;
                    a.setData({
                      kjgoods_list: t
                    });
                } else a.showToast({
                    title: o.msg
                });
            }
        });
},
loadShop: function () {
  var o = this, n = o.data.page;
  e || (e = !0, wx.showLoading({
    title: "加载中",
  }), getApp().request({
    url: getApp().api.mch.mch_list,
    method: "GET",
    data: {
      longitude: o.data.longitude,
      latitude: o.data.latitude
    },
    success: function (t) {
      if (0 == t.code) {
        var a = t.data.list;
        o.setData({
          shop: a
        });
      }
    },
    complete: function () {
      wx.hideLoading(), e = !1;
    }
  }));
 
},
navigatorShop:function(e){
  getApp().core.navigateTo({
    url: '/mch/shop/shop?mch_id=' + e.currentTarget.dataset.id
  });
},



  onCloseLoginModal: function () {
    this.setData({
      is_show_index_login_modal: false
    })
  },
  onAuthLogin: function () {
    setTimeout(() => {
      this.onCloseLoginModal()
    }, 200)
    wx.switchTab({
      url: '/pages/user/user',
    })
  },
  suspension: function() {
    var o = this;
    interval = setInterval(function() {
      getApp().request({
        url: getApp().api.default.buy_data,
        data: {
          time: o.data.time
        },
        method: "POST",
        success: function(t) {
          console.log(t,'砍价2')
          if (0 == t.code) {
            var a = !1;
            o.data.msgHistory == t.md5 && (a = !0);
            var e = "",
              i = t.cha_time,
              s = Math.floor(i / 60 - 60 * Math.floor(i / 3600));
            e = 0 == s ? i % 60 + "秒" : s + "分" + i % 60 + "秒", !a && t.cha_time <= 300 ? o.setData({
              buy: {
                time: e,
                type: t.data.type,
                url: t.data.url,
                user: 5 <= t.data.user.length ? t.data.user.slice(0, 4) + "..." : t.data.user,
                avatar_url: t.data.avatar_url,
                address: 8 <= t.data.address.length ? t.data.address.slice(0, 7) + "..." : t.data.address,
                content: t.data.content
              },
              msgHistory: t.md5
            }) : o.setData({
              buy: !1
            });
          }
        },
        noHandlerFail: !0
      });
    }, 1e4);
  },
  loadData: function() {
    wx.showLoading({
      title: "加载中"
    });
    var i = this,
      t = {},
      s = i.data.options;
    if (-1 != s.page_id) t.page_id = s.page_id;
    else {
      t.page_id = -1;
      var a = getApp().core.getStorageSync(getApp().const.PAGE_INDEX_INDEX);
      a && (a.act_modal_list = [], i.setData(a));
    }
    getApp().request({
      url: getApp().api.default.index,
      data: t,
      success: function(t) {
        if (0 == t.code) {
          if ("diy" == t.data.status) {
            var a = t.data.act_modal_list; -
            1 != s.page_id && (getApp().core.setNavigationBarTitle({
              title: t.data.info
            }), i.setData({
              title: t.data.info
            }));
            for (var e = a.length - 1; 0 <= e; e--)(void 0 === a[e].status || 0 == a[e].status) && getApp().helper.inArray(a[e].page_id, page_first) && !i.data.user_info_show || 0 == a[e].show ? a.splice(e, 1) : page_first.push(a[e].page_id);
            i.setData({
              template: t.data.template,
              act_modal_list: a,
              time_all: t.data.time_all,
              store: t.data.store
            }), i.setTime();
          } else page_first_init ? i.data.user_info_show || (page_first_init = !1) : t.data.act_modal_list = [],
            i.setData(t.data), i.miaoshaTimer(); -
          1 == s.page_id && getApp().core.setStorageSync(getApp().const.PAGE_INDEX_INDEX, t.data);
        }
      },
      complete: function() {
        wx.hideLoading();
        getApp().core.stopPullDownRefresh();
      }
    });
  },
  onShow: function() {
    var e = this;
    getApp().page.onShow(this), require("./../../components/diy/diy.js").init(this),
      getApp().getConfig(function(t) {
        var a = t.store;
        a && a.name && -1 == e.data.options.page_id && getApp().core.setNavigationBarTitle({
          title: a.name
        }), a && 1 === a.purchase_frame ? e.suspension(e.data.time) : e.setData({
          buy_user: ""
        });
      }), getApp().query = null;
      //site_info
    var n = getApp().core.getStorageSync(getApp().const.ADDRESS_INFO);
    if(n){
      e.setData({
        shop_info: {
          name: n.name,
          pic_url: n.pic_url
        }
      })
    }
    var user_info = getApp().getUser();
    // if (user_info && user_info.parent_mch_id > 0 &&  !getApp().globalData.is_first_index) {
    //  getApp().globalData.is_first_index = true;
    //   wx.redirectTo({
    //     url: '/mch/shop/shop?mch_id=' + user_info.parent_mch_id,
    //   });
    // } 
  },
  onPullDownRefresh: function() {
    getApp().getStoreData(), clearInterval(timer), this.loadData();
  },
  onShareAppMessage: function(t) {
    getApp().page.onShareAppMessage(this);
    var a = this,
      e = getApp().getUser();
    var share_param = {
      path: -1 != a.data.options.page_id ? "/pages/index/index?user_id=" + e.id + "&page_id=" + a.data.options.page_id + '&store_id=' + (wx.getStorageSync("store_id") ? wx.getStorageSync("store_id") : 0) : "/pages/index/index?user_id=" + e.id + '&store_id=' + (wx.getStorageSync("store_id") ? wx.getStorageSync("store_id") : 0),
      title: a.data.store.store_share_title ? a.data.store.store_share_title : a.data.store.name,
    };
    if (a.data.store.store_share_logo) {
      share_param.imageUrl = a.data.store.store_share_logo;
    }
    return share_param;
  },
  showshop: function(t) {
    var a = this,
      e = t.currentTarget.dataset.id,
      i = t.currentTarget.dataset;
    getApp().request({
      url: getApp().api.default.goods,
      data: {
        id: e
      },
      success: function(t) {
        console.log(t,'砍价4')
        0 == t.code && a.setData({
          data: i,
          attr_group_list: t.data.attr_group_list,
          goods: t.data,
          showModal: !0
        });
      }
    });
  },
  //调用扫码接口
  onAddCart: function () {
    wx.scanCode({
        success: (res) => {
            var no = res.result;
            getApp().request({
                url: getApp().api.cart.find_goods,
                data: {
                    no: no
                },
                method: 'POST',
                success: function (res) {
                  if (res.code == 1) {
                    return getApp().core.showToast({
                      title: "未找到商品",
                      icon:'none'
                    })
                  }
                  //查询到商品后执行添加线下购物车操作
                  var id = res.data.id;
                  var str = res.data.return_str;
                  getApp().request({
                      url: getApp().api.cart.add_cart_offline,
                      data: {
                          goods_id: id,
                          attr: str,
                          num: 1
                      },
                      method: 'POST',
                      success: function (res) {
                          //跳转到线下购物车页面
                          if (res.code == 0) {
                            wx.showToast({
                              title: res.msg,
                            })
                            getApp().core.navigateTo({
                                url: "/pages/cartoffline/cartoffline"
                            });
                          }

                      }
                  });
                }
            });
        }
    })
},
  miaoshaTimer: function() {
    var t = this;
    t.data.miaosha && 0 != t.data.miaosha.rest_time && (t.data.miaosha.ms_next || (timer = setInterval(function() {
      0 < t.data.miaosha.rest_time ? (t.data.miaosha.rest_time = t.data.miaosha.rest_time - 1,
        t.data.miaosha.times = t.setTimeList(t.data.miaosha.rest_time), t.setData({
          miaosha: t.data.miaosha
        })) : clearInterval(timer);
    }, 1e3)));
  },
  onHide: function() {
    getApp().page.onHide(this), this.setData({
      play: -1
    }), clearInterval(interval);
  },
  onUnload: function() {
    getApp().page.onUnload(this), this.setData({
      play: -1
    }), clearInterval(timer), clearInterval(interval), clearInterval(timer1);
  },
  showNotice: function(t) {
    console.log(t), this.setData({
      show_notice: t.currentTarget.dataset.index
    });
  },
  closeNotice: function() {
    this.setData({
      show_notice: -1
    });
  },
  to_dial: function() {
    var t = this.data.store.contact_tel;
    getApp().core.makePhoneCall({
      phoneNumber: t
    });
  },
  closeActModal: function() {
    var a = this,
      e = a.data.act_modal_list;
    for (var t in e) {
      var i = parseInt(t);
      e[i].show && (e[i].show = !1);
      break;
    }
    a.setData({
      act_modal_list: e
    }), setTimeout(function() {
      for (var t in e)
        if (e[t].show) {
          e = e.splice(t, 1).concat(e);
          break;
        }
      a.setData({
        act_modal_list: e
      });
    }, 500);
  },
  naveClick: function(t) {
    getApp().navigatorClick(t, this);
  },
  onPageScroll: function(t) {
    var a = this;
    if (!fullScreen && -1 != a.data.play) {
      var e = systemInfo.windowHeight;
      "undefined" == typeof my ? getApp().core.createSelectorQuery().select(".video").fields({
        rect: !0
      }, function(t) {
        (t.top <= -200 || t.top >= e - 57) && a.setData({
          play: -1
        });
      }).exec() : getApp().core.createSelectorQuery().select(".video").boundingClientRect().scrollOffset().exec(function(t) {
        (t[0].top <= -200 || t[0].top >= e - 57) && a.setData({
          play: -1
        });
      });
    }
  },
  fullscreenchange: function(t) {
    fullScreen = !!t.detail.fullScreen;
  },
  onShareTimeLine: function() {
    var a = this,
      e = getApp().getUser();
    var share_param = -1 != a.data.options.page_id ? {
      title: a.data.store.store_share_title ? a.data.store.store_share_title : a.data.store.name,
      query: 'page_id=' + a.data.options.page_id + '&user_id=' + e.id + '&store_id=' + (wx.getStorageSync("store_id") ? wx.getStorageSync("store_id") : 0)
    } : {
      title: a.data.store.store_share_title ? a.data.store.store_share_title : a.data.store.name,
      query: 'user_id=' + e.id + '&store_id=' + (wx.getStorageSync("store_id") ? wx.getStorageSync("store_id") : 0)
    };
    if (a.data.store.store_share_logo) {
      share_param.imageUrl = a.data.store.store_share_logo;
    }
    return share_param;
  }
});